const { writeLog } = require('../utils/index');

const errorHandler = async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    const errorMessage = err.message || err.toString() || "Unknown Error";
    ctx.body = {
      code: ctx.status,
      data: null,
      success: false,
      message: errorMessage,
    };
    ctx.app.emit("error", err, ctx);

    // Log error to file
    writeLog('error', errorMessage);
  }
};

module.exports = errorHandler;